<template>
  <van-nav-bar title="烹饪步骤" left-text="返回" left-arrow @click-left="() => { router.back() }" />
  <div v-if="display" class="inputCook">
    <div class="pic">
      <img src="../assets/inputCook.png" alt="">
    </div>
    <input type="text" placeholder="请输入菜品名称" v-model="dishName">
    <van-button class="btn" type="primary" color="#FF6B6B" @click="cookStep">开始生成</van-button>
  </div>
  <div v-else class="main">
    <foodStep :msg="data"></foodStep>
    <van-button v-debounce="add" type="primary" size="large">添加到我的食谱</van-button>
  </div>
</template>

<script setup>
import foodStep from '@/components/foodStep.vue'
import router from '@/router/index.js'
import { isLogin } from '@/utils/isLogin.js'
import { showSuccessToast, showToast, showLoadingToast, closeToast, showFailToast } from 'vant';
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { generateStep, addCook } from '@/api'
import { generateImg } from '@/api/index.js'

const route = useRoute()
const dishName = ref('')
const display = ref(true)
const data = ref(null)

// 检查是否通过路径或查询参数传递了菜名
onMounted(() => {
  const passedDishName = route.query.dishName;
  if (passedDishName) {
    dishName.value = decodeURIComponent(passedDishName); // 解码可能的URL编码
    cookStep(); // 自动调用方法开始生成步骤
  }
});

async function retry() {
  let count = 0;
  let res = null;
  const repeat = async () => {
    const result = await generateStep(dishName.value);
    try {
      console.log(result.msg);
      res = JSON.parse(result.msg);
      return res; // 确保在成功时返回解析后的结果
    } catch (error) {
      count++;
      console.log(`第${count}次失败`);
      if (count >= 3) { // 确保重试三次
        showToast('生成格式有误，请重试');
        throw new Error('Maximum retry reached'); // 抛出错误以便上层捕获
      }
      return repeat(); // 确保递归调用返回其结果
    }
  };

  try {
    return await repeat(); // 确保捕获 repeat 的返回值
  } catch (error) {
    console.error(error);
    return null; // 在捕获到错误时返回 null 或其他适当的值
  }
}

const cookStep = async () => {
  // 显示加载中的提示
  showLoadingToast({
    message: 'AI生成步骤中',
    duration: 0
  });

  const res = await retry()
  console.log(res, 451565626);


  try {
    let imgurl = await generateImg(`${res.name}`, "1344x768")
    console.log(imgurl);
    res.image = imgurl.url
  } catch {
    res.image = 'https://aigc-files.bigmodel.cn/api/cogview/20250307235443f290102e30d64ee6_0.png'
  }
  async function generateImage() {
    for (let i = 0; i < res.steps.length; i++) {
      const imgUrl = await generateImg(`${res.steps[i].description}`, "1152x864")
      res.steps[i].img_url = imgUrl.url
    }
  }

  await generateImage()

  if (res) {
    closeToast();
    data.value = res;
    display.value = false;
    // 请求成功后显示成功的提示
    showSuccessToast('生成步骤成功');
    console.log(data.value, 12121212121212);

  } else {
    showToast('未能获取到烹饪步骤，请稍后再试');
  }
};

const add = async () => {
  // 向后端发送一个请求，用户的 id
  // 登录问题
  // 跳去登录页面
  if (isLogin()) {
    const userInfoString = localStorage.getItem('userInfo');
    const userInfo = JSON.parse(userInfoString)
    const res = await addCook({
      userId: userInfo.id,
      steps: data.value
    })
    console.log(res);

    if (res.note === 2) {
      showSuccessToast(res.message)
    } else if (res.note === 1) {
      showFailToast(res.message);
    } else {
      showFailToast(res.message)
    }
  } else {
    router.push({ path: '/login' })
    showToast('请先登录')
  }
}
</script>

<style lang="less" scoped>
.inputCook {
  margin: 10px 20px;

  .pic {
    height: 200px;
    width: 100%;
    display: flex;
    justify-content: center;

    img {
      height: 100%;
      margin: 0 auto;
    }
  }

  input {
    width: 100%;
    height: 45px;
    border: 1px solid #E5E7EB;
    border-radius: 12px;
    padding: 0 16px;
    box-sizing: border-box;
    font-size: 15px;
  }

  ::placeholder {
    color: #9CA3AF;
    font-size: 15px;
    font-weight: normal;
  }

  .btn {
    margin-top: 20px;
    width: 100%;
  }
}

.main {
  background-color: #F0F1F2; // 设置整个页面的背景颜色
  min-height: 100vh; // 确保有足够的高度覆盖整个视口
}
</style>